package com.evan.designpatterns.observer.refactor.event;

import com.evan.designpatterns.observer.refactor.Question;
import com.evan.designpatterns.observer.refactor.event.abstracts.Event;
import com.evan.designpatterns.observer.refactor.event.abstracts.IAllTeacherEvent;
import com.evan.designpatterns.observer.refactor.event.abstracts.ISingleTeacherEvent;
import org.clapper.util.classutil.ClassFilter;
import org.clapper.util.classutil.ClassFinder;
import org.clapper.util.classutil.ClassInfo;
import org.clapper.util.classutil.SubclassClassFilter;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author :liujiapeng01
 * @date :2019-03-19 17:46
 **/
public class AllTeacherEvent extends IAllTeacherEvent {

    private static Collection<ClassInfo> foundClasses = new ArrayList<>();

    static {
        ClassFinder classFinder = new ClassFinder();
        ClassFilter filter = new SubclassClassFilter(ISingleTeacherEvent.class);
        classFinder.addClassPath();
        classFinder.findClasses(foundClasses, filter);
    }

    public AllTeacherEvent(Question question) {
        super(question);
    }

    @Override
    public void publish() {
        foundClasses.stream().map(ClassInfo::getClassName).forEach(item -> {
            try {
                Class<?> clazz = Class.forName(item);
                Constructor<?> constructor = clazz.getConstructor(Question.class);
                Event instance = (Event) constructor.newInstance(this.getQuestion());
                instance.publish();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

    }


}
